package com.syezon.wifikey.splash.tt;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.syezon.wifikey.BuildConfig;
import com.syezon.wifikey.R;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.config.TTAdManagerHolder;
import com.syezon.wifikey.splash.SplashNewCallBack;


import butterknife.BindView;
import butterknife.ButterKnife;

public class TTNewSplashFragment extends Fragment implements TTSplashAdListener {

    private static final String TAG = TTSplashFragment.class.getSimpleName();
    private static final int SPLASH_LOAD_TIME = 3;
    private static final int SPLASH_SHOW_TIME = 5;
    private static int minSplashTimeWhenNoAD = 2000;
    private static final int MSG_SPLASH_DOWN_COUNT = 1;
    public boolean canJump = false;
    private int times = SPLASH_LOAD_TIME;
    private static final String SKIP_TEXT = "点击跳过 %d";
    private static final String SPLASH_AD_INFO = "splash_ad_info";

    /**
     * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
     * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
     * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值（单位ms）
     **/
    /**
     * 记录拉取广告的时间
     */
    private long fetchSplashADTime = 0;
    private Handler handler = new Handler(Looper.getMainLooper());
    @BindView(R.id.view_logo_bottom)
    View mViewBottom;
    @BindView(R.id.fl_container)
    FrameLayout mFlContainer;
    @BindView(R.id.tv_skip)
    TextView mSkipView;
    @BindView(R.id.iv_hold)
    ImageView mIvHold;

    private AdInfo adInfo;
    private TTAdNative mTTAdNative;

    private SplashNewCallBack mListener;
    private boolean mLoadAd;
    private boolean mReportShow;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SPLASH_DOWN_COUNT:
                    mSkipView.setText(String.format(SKIP_TEXT, times));
                    if (times <= 0) {
                        mHandler.removeMessages(MSG_SPLASH_DOWN_COUNT);
                        if (!mLoadAd) {
                            onNoAD("加载超时了");
                        } else {
                            next();
                        }
                        return;
                    } else {
                        times--;
                        mHandler.sendEmptyMessageDelayed(MSG_SPLASH_DOWN_COUNT, 1000);
                    }
                    break;
            }

        }
    };

    public TTNewSplashFragment() {
    }

    public static TTNewSplashFragment newInstance(AdInfo adInfo) {
        TTNewSplashFragment fragment = new TTNewSplashFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(SPLASH_AD_INFO, adInfo);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            adInfo = getArguments().getParcelable(SPLASH_AD_INFO);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.app_splash_fragment_tt, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
        init();
    }

    private void init() {
//        mHandler.sendEmptyMessage(MSG_SPLASH_DOWN_COUNT);
        mSkipView.setVisibility(View.GONE);
        getAdData();
    }

    public void getAdData() {
        fetchSplashADTime = System.currentTimeMillis();
        mTTAdNative = TTAdManagerHolder.get().createAdNative(getActivity());
        loadSplashAd();
    }

    /**
     * 加载开屏广告
     */
    private void loadSplashAd() {
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adInfo.getCode())
                .setSupportDeepLink(false)
                .setImageAcceptedSize(1080, 1920)
                .build();
        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            @Override
            @MainThread
            public void onError(int code, String message) {
                Log.d(TAG, message);
                mLoadAd = false;
                if (BuildConfig.DEBUG) {
//                    ToastUtils.showShort("穿山甲  加载失败了  onError    message:" + message + "    code:" + code);
                    LogUtils.e("loadSplashAd  穿山甲加载失败 onError       message:" + message + " code:" +  code);
                }
                onNoAD(message);
                ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            }

            @Override
            @MainThread
            public void onTimeout() {
                onNoAD("timeOut");
                if (BuildConfig.DEBUG) {
//                    ToastUtils.showShort("穿山甲  加载失败 onTimeout 网络连接超时");
                    LogUtils.e("loadSplashAd  穿山甲加载失败 onTimeout");
                }
                ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            }

            @Override
            @MainThread
            public void onSplashAdLoad(TTSplashAd ad) {
                Log.d(TAG, "开屏广告请求成功");
                if (ad == null || isDetached()) {
                    return;
                }
                //获取SplashView
                View view = ad.getSplashView();
                mFlContainer.removeAllViews();
                //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕宽
                mFlContainer.addView(view);
//                onADPresent();
                //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                ad.setNotAllowSdkCountdown();
                //设置SplashView的交互监听器
                mLoadAd = true;
                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {
                        onADClicked();
                    }

                    @Override
                    public void onAdShow(View view, int type) {
                        onADPresent();
                    }

                    @Override
                    public void onAdSkip() {
                        next();
                    }

                    @Override
                    public void onAdTimeOver() {
                        onADDismissed();
                    }
                });
                ad.setDownloadListener(new TTAppDownloadListener() {

                    boolean reportDownload;
                    boolean reportInstall;

                    @Override
                    public void onIdle() {

                    }

                    @Override
                    public void onDownloadActive(long l, long l1, String s, String s1) {

                    }

                    @Override
                    public void onDownloadPaused(long l, long l1, String s, String s1) {

                    }

                    @Override
                    public void onDownloadFailed(long l, long l1, String s, String s1) {

                    }

                    @Override
                    public void onDownloadFinished(long l, String s, String s1) {
                        if (!reportDownload) {
                            reportDownload = true;
                            ReportAgent.reportAdvDownload(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                        }
                    }

                    @Override
                    public void onInstalled(String s, String s1) {
                        if (!reportInstall) {
                            reportInstall = true;
                            ReportAgent.reportAdvInstall(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());                        }
                    }
                });
            }
        }, 1500);
    }

    @Override
    public void onADPresent() {
        mHandler.removeMessages(MSG_SPLASH_DOWN_COUNT);
        times = SPLASH_SHOW_TIME;
        mHandler.sendEmptyMessage(MSG_SPLASH_DOWN_COUNT);
        mSkipView.setVisibility(View.VISIBLE);
        mSkipView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onADDismissed();
            }
        });
        mIvHold.setVisibility(View.GONE);
        if (mListener != null) {
            mListener.onLoadSuccess(adInfo);
        }

        if (!mReportShow) {
            mReportShow = true;
            ReportAgent.reportAdvExtShow(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
        }
    }

    @Override
    public void onADClicked() {
        ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
    }

    /**
     * 倒计时回调，返回广告还将被展示的剩余时间。
     * 通过这个接口，开发者可以自行决定是否显示倒计时提示，或者还剩几秒的时候显示倒计时
     *
     * @param millisUntilFinished 剩余毫秒数
     */
    @Override
    public void onADTick(long millisUntilFinished) {
    }

    @Override
    public void onADExposure() {
    }

    @Override
    public void onADDismissed() {
        next();
    }

    @Override
    public void onNoAD(String errorMsg) {
        if (mListener != null) {
            mHandler.removeMessages(MSG_SPLASH_DOWN_COUNT);
            mListener.onLoadFail(adInfo, errorMsg);
            return;
        }
        /**
         * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
         * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
         * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
         **/
        long alreadyDelayMills = System.currentTimeMillis() - fetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
        long shouldDelayMills = alreadyDelayMills > minSplashTimeWhenNoAD ? 0 : minSplashTimeWhenNoAD
                - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
        // 计算出还需要延时多久
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mListener != null) {
                    mListener.goMain();
                }
            }
        }, shouldDelayMills);
    }

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */

    private void next() {
        if (canJump) {
            if (mListener != null) {
                mListener.goMain();
            }
        } else {
            canJump = true;
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (canJump) {
            next();
        }
        canJump = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            handler.removeCallbacksAndMessages(null);
            mHandler.removeCallbacksAndMessages(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof SplashNewCallBack) {
            mListener = (SplashNewCallBack) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement SplashCallBack");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

}
